package com.notepad.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.notepad.blog.common.api.ApiResult;
import com.notepad.blog.common.exception.ApiAsserts;
import com.notepad.blog.common.utils.MD5Utils;
import com.notepad.blog.config.jwt.JwtUtil;
import com.notepad.blog.domain.BmsFollow;
import com.notepad.blog.domain.BmsPost;
import com.notepad.blog.domain.BmsPostTag;
import com.notepad.blog.domain.UmsUser;
import com.notepad.blog.domain.dto.LoginDTO;
import com.notepad.blog.domain.dto.RegisterDTO;
import com.notepad.blog.domain.vo.ProfileVO;
import com.notepad.blog.mapper.BmsFollowMapper;
import com.notepad.blog.mapper.BmsPostMapper;
import com.notepad.blog.mapper.UmsUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UmsUserService
 * @description:
 * @author: 一粒麦子
 * @Date 2021/2/11 23:28
 **/
@Service
public class UmsUserService extends ServiceImpl<UmsUserMapper, UmsUser> {

    /**
     * 注册
     *
     * @param registerDTO 接收参数
     * @return
     */
    public Boolean register(RegisterDTO registerDTO) {
        // 查询是否有相同的用户名
        String userName = registerDTO.getName();
        String email = registerDTO.getEmail();
        LambdaQueryWrapper<UmsUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsUser::getUsername, userName)
                .or()
                .eq(UmsUser::getEmail, userName);
        UmsUser umuser = this.getOne(queryWrapper);
        if (!ObjectUtils.isEmpty(umuser)) {
            ApiAsserts.fail("账号或邮箱已存在");
        }

        // 否则注册
        UmsUser umsUser = UmsUser.builder()
                .username(userName)
                .alias(userName)
                .password(MD5Utils.getPwd(registerDTO.getPass()))
                .email(email)
                .createTime(new Date())
                .status(true)
                .build();
        return this.save(umsUser);
    }

    /**
     * 登录
     *
     * @param loginDTO
     * @return
     */
    public Map<String, String> login(LoginDTO loginDTO) {

        // 邮箱或用户名是否存在
        String loginUserName = loginDTO.getUsername();
        UmsUser umsUser = this.getOne(new LambdaQueryWrapper<UmsUser>()
                .eq(UmsUser::getUsername, loginUserName)
                .or()
                .eq(UmsUser::getEmail, loginUserName));
        if (ObjectUtils.isEmpty(umsUser)) {
            ApiAsserts.fail("用户名或邮箱不存在");
        }

        // 校验密码
        if (!MD5Utils.getPwd(loginDTO.getPassword()).equals(umsUser.getPassword())) {
            ApiAsserts.fail("密码错误，请重新输入");
        }

        // 生成 token
        String token = JwtUtil.generateToken(loginUserName);

        HashMap<String, String> map = new HashMap<>(16);
        map.put("token", token);
        return map;
    }

    @Autowired
    private BmsPostMapper postMapper;

    @Autowired
    private BmsFollowMapper followMapper;

    public ProfileVO getUserProfile(String userId) {
        ProfileVO profile = new ProfileVO();
        UmsUser user = baseMapper.selectById(userId);
        BeanUtils.copyProperties(user, profile);
        // 用户文章数
        int count = postMapper.selectCount(new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getUserId, userId));
        profile.setTopicCount(count);

        // 粉丝数
        int followers = followMapper.selectCount((new LambdaQueryWrapper<BmsFollow>().eq(BmsFollow::getParentId, userId)));
        profile.setFollowerCount(followers);
        return profile;
    }
}
